﻿using MesBSW.DAL.RoleDB;
using MesBSW.DAL.RoleDTO;
using MesBSW.Tools;
using MesBSW.View;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;


namespace MesBSW.BLL.Role
{
    public class UserInfoControler
    {

        public List<BaseUserModel> SearchAllUser()
        {
            List<BaseUserModel> resList = new List<BaseUserModel>();
            using (RoleDB ctx = new RoleDB())
            {
                var query = ctx.base_user;
                if (query != null && query.Count() > 0)
                {
                    resList.AddRange(query);
                }
            }
            return resList;
        }

        public List<BaseDeptDTO> SearchAllDeptIntoList()
        {
            List<BaseDeptDTO> resList = new List<BaseDeptDTO>();
            using (RoleDB ctx = new RoleDB())
            {
                var query = ctx.base_dept;
                if (query != null && query.Count() > 0)
                {
                    foreach (var item in query)
                    {
                        BaseDeptDTO tmpDept = new BaseDeptDTO();
                        EntityTools.CopyEntity(item, ref tmpDept);
                        resList.Add(tmpDept);
                    }
                }
            }
            return resList;
        }

        public List<System.Windows.Forms.TreeNode> SearchAllDeptIntoNode()
        {
            List<System.Windows.Forms.TreeNode> resList = new List<System.Windows.Forms.TreeNode>();
            using (RoleDB ctx = new RoleDB())
            {
                var query = ctx.base_dept;
                if (query != null && query.Count() > 0)
                {
                    List<BaseDeptModel> deptList = query.ToList();
                    foreach (var tmpDept in deptList)
                    {
                        if (tmpDept.parent_id == 0 && tmpDept.is_del == false )
                        {
                            System.Windows.Forms.TreeNode tn = new System.Windows.Forms.TreeNode();
                            tn.Text = tmpDept.dept_name ;
                            tn.Tag = tmpDept.id.ToString();
                            resList.Add(tn);
                            this.SearchChildDept(deptList,tn);
                        }
                    }
                }
            }
            return resList; 
        }

        private void SearchChildDept(List<BaseDeptModel> deptList, System.Windows.Forms.TreeNode deptInfo)
        {
            if (deptList != null && deptList.Count > 0)
            {
                int deptID = int.Parse(deptInfo.Tag.ToString());
                var query = deptList.Where(d => d.parent_id == deptID);
                if (query != null && query.Count() > 0)
                {
                    foreach (var tmpDept in query)
                    {
                        if (tmpDept.is_del == false)
                        {
                            System.Windows.Forms.TreeNode tn = new System.Windows.Forms.TreeNode();
                            tn.Text= tmpDept.dept_name;
                            tn.Tag= tmpDept.id.ToString();
                            SearchChildDept(deptList,tn);
                            deptInfo.Nodes.Add(tn);
                        }
                    }
                }

            }
        }


        /// <summary>
        /// 根据用户名查询用户
        /// </summary>
        /// <param name="username">用户名</param>
        /// <returns></returns>
        public List<BaseUserDTO> SearchUserByUserName(string username)
        {
            List<BaseUserDTO> resList = new List<BaseUserDTO>();
            using (RoleDB ctx = new RoleDB())
            {
                var query = from a in ctx.base_user
                            join b in ctx.base_user_role on a.id equals b.base_user_id into tmp1
                            from ab in tmp1.DefaultIfEmpty()
                            join c in ctx.base_role on ab.base_role_id equals c.id into tmp2
                            from bc in tmp2.DefaultIfEmpty()
                            join d in ctx.base_dept on a.base_dept_id equals d.id into tmp3
                            from ad in tmp3.DefaultIfEmpty()
                            select new { user = a, role = bc, dept = ad };
                if (query != null && query.Count() > 0)
                {
                    foreach (var item in query)
                    {
                        BaseUserDTO tmpUser = new BaseUserDTO();
                        EntityTools.CopyEntity(item.user, ref tmpUser);
                        tmpUser.RoleModel = item.role ?? new BaseRoleModel();
                        tmpUser.deptModel = item.dept ?? new BaseDeptModel();
                        tmpUser.SexName = tmpUser.sex != null && tmpUser.sex == true ? "男" : "女";
                        resList.Add(tmpUser);
                    }
                    
                    if (username != null && username.Trim().Length > 0)
                    {
                        resList = resList.Where(u => u.user_name.Equals(username)).ToList();
                    }
                }
            }
            return resList;
        }

        /// <summary>
        /// 新增用户
        /// </summary>
        /// <param name="user">用户信息</param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public Boolean InsertUser(BaseUserModel user)
        {
            if (user != null)
            {
                using (RoleDB ctx = new RoleDB())
                {
                    //先查看要保存的用户信息是否已经存在，用户名不能重复
                    var query = ctx.base_user.Where(u => u.user_name.Equals(user.user_name));
                    if (query != null && query.Count() > 0)
                    {
                        throw new Exception("新增用户的用户名" + user.user_name + "已经存在，用户名不能重复，终止保存！");
                    }
                    else
                    {
                        user.id = 0;
                        user.create_user = MainFrm.LoginUser.user_name;
                        user.create_date = DateTime.Now;
                        ctx.base_user.Add(user);
                        if (ctx.SaveChanges() > 0)
                        {
                            return true;
                        }
                        else
                        {
                            return false;
                        }
                    }
                }
            }
            else
            {
                throw new Exception("传入的用户信息为空，无法保存！");
            }
        }


        public Boolean UpdateUser(BaseUserModel user)
        {
            if (user != null)
            {
                using (RoleDB ctx = new RoleDB())
                {
                    ctx.base_user.Attach(user);
                    ctx.Entry(user).State = EntityState.Modified;
                    if (ctx.SaveChanges() > 0)
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
            }
            else
            {
                throw new Exception("传入的用户信息为空，无法保存！");
            }
        }

        public List<BaseDeptModel> SearchAllDept()
        {
            using (RoleDB ctx = new RoleDB())
            {
                return ctx.base_dept.ToList();
            }
        }


        /// <summary>
        /// 查询可以使用特定界面的用户
        /// </summary>
        /// <param name="className">界面对应的类名</param>
        /// <returns></returns>
        public List<BaseUserModel> SearchUserForMuneClassName(string className) 
        { 
            List<BaseUserModel> resList = new List<BaseUserModel>();
            using (RoleDB ctx = new RoleDB())
            {
                var query = from a in ctx.base_user
                            join b in ctx.base_user_role on a.id equals b.base_user_id
                            join c in ctx.base_role on b.base_role_id equals c.id
                            join d in ctx.base_role_menu on c.id equals d.base_role_id
                            join e in ctx.base_menu on d.base_menu_id equals e.id
                            where e.class_name == className
                            select a;
                if (query != null && query.Count() > 0)
                {
                    resList.AddRange(query);
                }
            }
            return resList;
        }


        
    }
}
